<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/component/commonTagLib.jsp"%>
<!DOCTYPE html>
<html>
<head>
	<title><spring:message code="message.lable.TuiHuoJiHua"/></title>
	<%@ include file="/WEB-INF/component/commonCSS.jsp"%>
    <!--[if lt IE 9]>
        <script src="lib/js/html5shiv.min.js"></script>
        <script src="lib/js/respond.min.js"></script>
    <![endif]-->
</head>
<body class="skin-blue-light sidebar-mini fixed skin-blue-light-frame">
    <section class="content-header">
        <h1><spring:message code="message.list.ZhiDingTuiHuoDan"/></h1>
        <ol class="breadcrumb">
        	<li><a href="${ctx}/home.jsp"><i class="fa fa-home"></i><spring:message code="message.lable.first"/></a></li>
        	<li><a href="#">交易</a></li>
            <li><a href="#">药品退货</a></li>
            <li class="active"><a href="#"><spring:message code="message.list.ZhiDingTuiHuoDan"/></a></li>
        </ol>
    </section>
    
    <section class="content">
		<div class=" box box-success">
			<div class="box-body">
				 <form id="form" class="form-horizontal" action="submitOrder.html" method="post">
	                <input type="hidden" id="recpAddrId" name="recpAddrId" value="${address.recpAddrId}" />
	                <input type="hidden" id="plans" name="plans" />
	                <input type="hidden" id="confirm" name="confirm" />
				</form>
				 <div class="input">
                	<div class="textalign1"><spring:message code="message.listForm.tongYongMing"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="drugName" name="drugName" placeholder="<spring:message code="message.listForm.tongYongMing"/>/<spring:message code="message.listForm.pinYinMa"/>" />
                    </div>
                    <%--<div class="textalign"><spring:message code="message.listForm.yaoPinBianMa"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                        <input type="text" class="textinput" id="drugCode" name="drugCode"  placeholder="<spring:message code="message.listForm.yaoPinBianMa"/>" />
                    </div>--%>
                    <div class="textalign1"><spring:message code="message.listForm.shengChanQiYe"/><spring:message code="message.yanZheng.maoHao"/></div>
                    <div class="boxinput">
                         <input type="text" class="textinput" id="compName" name="compName"  placeholder="<spring:message code="message.listForm.shengChanQiYe"/>/<spring:message code="message.listForm.pinYinMa"/>" />
                    </div>
					<div class="textalign1"><spring:message code="message.listForm.PeiSongQiYe"/><spring:message code="message.yanZheng.maoHao"/></div>
	                <div class="boxinput">
	                    <input type="text" class="textinput" id=delCompName name="delCompName"  placeholder="<spring:message code="message.listForm.PeiSongQiYe"/>/<spring:message code="message.listForm.pinYinMa"/>" />
	                </div>
					<div class="textalign1" >
						<button type="button" onclick="gridSerch();" class="btn btn-success btn-sm" id="selectDicCompType"><spring:message code="message.button.seachSpacing"/></button>
					</div>
                 </div>
			</div>
		</div>
		<table class="jqgrid" id="gridlist"></table>
		<div id="gridpage"></div>
		<div class=" box box-warning bottongroup">
			<label id="batchModifyData" onclick="modifyReturnPlan()" class="btn btn-primary btn-sm"><spring:message code="message.button.saveSpacing"/></label>
			<button type="button" onclick="submitOrder(0);" class="btn btn-primary btn-sm"><spring:message code="message.button.ShengChengTuiHuoDan"/></button>
			<button type="button" onclick="deleteReturnPlan();" class="btn btn-danger btn-sm"><spring:message code="message.button.delete"/></button>
		</div>

	</section>
    <%@ include file="/WEB-INF/component/commonJS.jsp"%>
    <script type="text/javascript">
    //绑定回车
    $('#drugName,#drugCode,#compName,#delCompName').bind('keydown', function(event) {
        if (event.keyCode == "13") {
            $('#selectDicCompType').click();
        }
    });	
    $("#drugName").focus();//加载页面光标在第一个查询框内
    
    
        $(function () {
            	
            	 $("#gridlist").jqGrid({
                     url: "${ctx}/purReturnOrder/getReturnDrugPlanDataList.html",
                     mtype: "POST",
                     datatype: "json",
                     autowidth: true,
                     shrinkToFit: false,
              //       height: 290,
                     colNames: ['retPlanId',
                                'retPlanId',
                                '<spring:message code="message.listForm.TuiHuoMingXiBianHao"/>',
                                '<spring:message code="message.listForm.TuiHuoShuLiang"/>',
                                '<spring:message code="message.listForm.TuiHuoYuanYin"/>',
                                '<spring:message code="message.listForm.TuiHuoJinE"/>',
                                '',
                                '<spring:message code="message.listForm.PeiSongQiYe"/>',
                                '<spring:message code="message.listForm.tongYongMing"/>', 
                                '<spring:message code="message.listForm.jiXing"/>',
                                '<spring:message code="message.listForm.guiGe"/>',
                                '<spring:message code="message.listForm.zhuanHuanXiShu"/>',
                                '<spring:message code="message.listForm.baoZhuangDanWei"/>', 
                                '<spring:message code="message.listForm.shengChanQiYe"/>',
                                '国药准字',
                                '<spring:message code="message.listForm.TuiHuoJiHuaGenXinRen"/>',
                                
                                '<spring:message code="message.listForm.PiCiHao"/>',
                                '<spring:message code="message.listForm.DaoHuoShuLiang"/>',
                                '累计退货数量',
                                '有效期',
                                '<spring:message code="message.listForm.CaiGouJia"/>'
                                ],
                     colModel: [
						{ name: 'retPlanId', index: 'ship',hidden:true, width: 100,align:"center",sortable:false},
						{ name: 'recpInfoId', index: 'ship',hidden:true, width: 50,align:"right",sortable:false},
     					{ name: 'retDetailCode', index: 'ship',hidden:true, width: 100,align:"center",sortable:false},
     					{ name: 'retCount', index: 'ship', width: 80, align: "center", sortable:false },
     					{ name: 'retReason', index: 'ship', width: 200,align:"center",sortable:false},
     					{ name: 'retMoney', index: 'ship', width: 80,align:"right",sortable:false},
     					{ name: 'delCompCode', index: 'ship',hidden:true, width: 100,align:"center",sortable:false},
     					 { name: 'delCompName', index: 'ship', width: 150, align: "center", sortable:false},
                         { name: 'qualityspecName', index: 'name', width: 120, align: "center" ,sortable:false },
                         { name: 'formName', index: 'stock', width: 60 , align: "center",sortable:false},
                         { name: 'specName', index: 'ship', width: 80, align: "center" ,sortable:false},
                         { name: 'factor', index: 'ship', width: 60, align: "center",sortable:false },
                         { name: 'unitName', index: 'ship', width: 60, align: "center",sortable:false },
                         { name: 'prodCompname', index: 'ship', width: 160, align: "center",sortable:false},
                     	{ name: 'drugMedicine', index: 'drugMedicine',width: 100, align: "center", sortable:false},
                         { name: 'updUser', index: 'sdate',hidden:true, width: 100, align: "center", sortable:false},
                         
                          { name: 'approveCode', index: 'sdate', width: 150, align: "center",sortable:false},
                          { name: 'totalAmount', index: 'sdate', width: 80, align: "center",sortable:false},
                          { name: 'returnCount', index: 'sdate', width: 100, align: "center",sortable:false,
                               formatter:function(cellvalue, options, row){
                                   return "<input class='gridText returnCount' id='returnCount"+row.retPlanId+"' type='hidden' maxlength='11' value='"+row.returnCount+"'/>"+row.returnCount;
                               }  
                          },
                          { name: 'credential', index: 'sdate', width: 150, align: "center",sortable:false},
                          { name: 'proPrice', index: 'ship', width: 50,align:"right", sortable:false,
                              formatter:function(cellvalue, options, row){
                                  return formatAmount(cellvalue, options, row);
                              }
                          }
                         
                     ],
                     
                     rowNum: -1,
                    // rowList: [10, 20, 50, 100],
                     rownumbers: true,
                     //pager: "#gridpage",
                     multiselect: true, 
                     viewrecords: true,
                     gridComplete: function(){
                        	 //序号列宽度自适应（参数为jqgridID）
                               autoRNWidth("gridlist");
                           	//数据只有一条时默认选中（参数为jqgridID）
                               selectByOneData("gridlist");
                    	 
                 		 var ids = jQuery("#gridlist").jqGrid('getDataIDs');
                 		for(var i=0;i < ids.length;i++){
                 			var id = ids[i];
                 			var rowdata = $("#gridlist").jqGrid('getRowData', id);
                 			a = "<input class=\"gridText reasonCount\"  type=\"text\" id=\"retReason"+id+"\" value=\""+rowdata.retReason+"\" />";
                 			b = "<input class=\"gridText retCount\"  type=\"text\" id=\"retCount"+id+"\" value=\""+rowdata.retCount+"\" />";
                 			jQuery("#gridlist").jqGrid('setRowData',ids[i],{retReason:a,retCount:b});
                 		}	
                        
                        $('.retCount').keyup(function(event){
                        	var num =$(this).attr("id").replace((/[^0-9]/ig),"");
                        	changeSelectChecked("#gridlist",num,$(this).val(),event);
                        }); 
                 		
                 	},
                     caption: "药品列表",
                     jsonReader: {
                         repeatitems: false,
                         id: "ids"
                     }
                 });
                 $("#gridlist").jqGrid('navGrid', '#gridpage', { add: false, edit: false, del: false, search: false, refresh: false });
                 $(window).trigger("resize");
                 $("#gridlist").jqGrid("setGridHeight", create());
             });
             
             //查询
             function gridSerch() {
             	var drugCode = $.trim($("#drugCode").val());
             	var drugName = $.trim($("#drugName").val());
             	var compName = $.trim($("#compName").val());
             	var delCompName = $.trim($("#delCompName").val());
         		$("#gridlist").jqGrid('setGridParam',{  
         	        datatype:'json',
         	        postData:{
         	        		"delCompName":delCompName,
         	        		"drugCode":drugCode,
         	        		"drugName":drugName,
         	        		"compName":compName},
         	        		page:1
         	    }).trigger("reloadGrid"); //重新载入  
         	}
        
             
           //删除
             function deleteReturnPlan(){
     		    var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
     			if (rowIds.length <= 0) {
     				$.HN.message.alert("请选择要刪除的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
     				return;
     			}
				var approveCodes = '';
	            for (var i=0; i<rowIds.length; i++) {
	                rowId = rowIds[i];
		    		var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
					if(i<3){
						approveCodes+= rowdata.approveCode+"<br/>"
						if(i==2)
						approveCodes+='...';
							
					}
				}
				
     			$.HN.message.confirm('确定删除以下批次号吗？<br/>'+approveCodes, '', '').on(function (e) {
                    if (e) {
     			var list = [];
     			for (var i=0; i<rowIds.length; i++) {
     				rowId = rowIds[i];
     				var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
     				list.push({"retPlanId":rowdata.retPlanId,"returnCount":$.trim($("#returnCount"+rowdata.retPlanId).val()),"recpInfoId":rowdata.recpInfoId}); 
     			}
     			$.post("${ctx}/purReturnOrder/deleteReturnPlan.html", {
     				"array" : json.jsonToString(list)
     				}, function(result) {
     					if (result.success) {
     						$.HN.message.alert("刪除成功！", "<spring:message code="message.HN.alert.type"/>", "success");
     						gridSerch();
     					} else {
     						$.HN.message.alert("删除失败！", "<spring:message code="message.HN.alert.type"/>", "error");
     					}
     				}, "json")
     				}});
     		}
             
            
             //生成退货订单
			function submitOrder(confirm) {
	    	$("#confirm").val(confirm);
		    	var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
	    		if (rowIds.length <= 0) {
	    			$.HN.message.alert("请选择要生成订单的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
	    			return;
	    		}
	    		var approveCodes = '';
	    		var reg = new RegExp(regexEnum.intege1);
		    	var list = [];
	    		for (var i=0; i<rowIds.length; i++) {
	    			rowId = rowIds[i];
	    			var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
	    			if ($.trim($("#retCount"+rowId).val()).length < 1){
	    			$.HN.message.alert("<spring:message code='message.yanZheng.QingTianXieTuiHuoShuLiang'/>", "<spring:message code='message.HN.alert.type'/>", "warn");
	    				return;
	    			} 
	    			if(!reg.test($.trim($("#retCount"+rowId).val()))){
                        $.HN.message.alert("<spring:message code='message.yanZheng.TuiHuoSLDaYuLing'/><spring:message code='message.yanZheng.qingChongXinShuRu'/>", "<spring:message code='message.HN.alert.type'/>", "warn");
                        return;
                    }
	    			if( parseInt( $.trim($("#retCount"+rowId).val())) + parseInt( $.trim($("#returnCount"+rowdata.retPlanId).val())) > rowdata.totalAmount ){
                        $.HN.message.alert('<spring:message code="message.yanZheng.TuiHuoSLNotDaYuDaoHSL"/>', '<spring:message code="message.HN.alert.type"/>', 'warn');
                         return;
                    }
	    			if ($.trim($("#retReason"+rowId).val()).length < 1){
	    			$.HN.message.alert('<spring:message code="message.yanZheng.QingTianXieTuiHuoYuanY"/>', "<spring:message code='message.HN.alert.type'/>", "warn");
	    				return;
	    			}
	    			if ($.trim($("#retReason"+rowId).val()).length > 300){
		    			$.HN.message.alert('退货原因最大长度为300', "<spring:message code='message.HN.alert.type'/>", "warn");
		    				return;
		    			}
	    			 list.push({"retPlanId":rowdata.retPlanId,"proPrice":rowdata.proPrice,"delCompCode":rowdata.delCompCode,"returnCount":$.trim($("#returnCount"+rowdata.retPlanId).val()),"retCount":$.trim($("#retCount"+rowId).val()),"recpInfoId":rowdata.recpInfoId,"retReason":$.trim($("#retReason"+rowId).val())});
					 if(i<3){
						approveCodes+= rowdata.approveCode+"<br/>"
						if(i==2)
						approveCodes+='...';
							
					}
	    		}
	    		
	    		$.HN.message.confirm('确定生成以下批次号退货单吗？<br/>'+approveCodes, '', '').on(function (e) {
                    if (e) {
		    	$.post("${ctx}/purReturnOrder/createReturnInfo.html", {
	    			"plans" : json.jsonToString(list),"confirm":confirm
	    		}, function(result) {
	    			if (result.success) {
                        $.HN.message.alert("提交成功！", "<spring:message code="message.HN.alert.type"/>", "success", function() {
                            /* top.mainframe.document.location = "${ctx}/purReturnOrder/toHospReturnInfoList.html"; */
                            gridSerch();
                        });
                    } else if (result.code == 10001) {
                        $.HN.message.alert("<spring:message code='message.yanZheng.GouWuJiHuaYiTiJiao'/><spring:message code='message.yanZheng.douhao'/><spring:message code='message.yanZheng.QingWuChongFuTiJiao'/>'", "<spring:message code='message.HN.alert.type'/>", "error");
                    } else if (result.code == 10002) {
                        $.HN.message.confirm("<spring:message code='message.yanZheng.BFGouWuJiHuaYiTiJiao'/><spring:message code='message.yanZheng.douhao'/><spring:message code='message.yanZheng.QueDingTiJiaoSYGWJiHuaMa'/><spring:message code='message.yanZheng.wenHao'/>", "<spring:message code='message.HN.alert.type'/>", "<spring:message code='message.button.confirm'/>").on(function(bool) {
                            if (bool) {
                            	submitOrder(1);
                            }
                        });
                    } else {
                        $.HN.message.alert(result.msg || "提交失败！", "<spring:message code="message.HN.alert.type"/>", "error");
                    }
	    		}, "json").error(function(err) {
	    		});
		    	}});
	   		 }
       
           //回调
    		 function operResult(val){
    	        	var strs = new Array();
    	            strs = val.split("|$");
    	            
    	            	if (val.length>0) {
    						$('#'+strs[0]).val(strs[2]);
    					}
    					if (val.length>0) {
    						$('#'+strs[1]).html(strs[3]);
    					}
    	        }
           
    		//保存
				function modifyReturnPlan() {
					var rowIds = $("#gridlist").jqGrid("getGridParam", "selarrrow") || [];
					if(rowIds.length <=0){
						$.HN.message.alert("请选择要保存的药品！", "<spring:message code="message.HN.alert.type"/>", "warn");
						return;
					}
					
					
					var reg = new RegExp(regexEnum.intege1);
	                var list = [];
					var approveCodes = '';
	                for (var i=0; i<rowIds.length; i++) {
	                	rowId = rowIds[i];
		    			var rowdata = $("#gridlist").jqGrid('getRowData', rowId);
		    			if ($.trim($("#retCount"+rowId).val()).length < 1){
		    			$.HN.message.alert("<spring:message code='message.yanZheng.QingTianXieTuiHuoShuLiang'/>", "<spring:message code='message.HN.alert.type'/>", "warn");
		    				return;
		    			} 
		    			if(!reg.test($.trim($("#retCount"+rowId).val()))){
	                        $.HN.message.alert("<spring:message code='message.yanZheng.TuiHuoSLDaYuLing'/><spring:message code='message.yanZheng.qingChongXinShuRu'/>", "<spring:message code='message.HN.alert.type'/>", "warn");
	                        return;
	                    }
		    			
		    			if( parseInt( $.trim($("#retCount"+rowId).val())) + parseInt( $.trim($("#returnCount"+rowdata.retPlanId).val())) > rowdata.totalAmount ){
	                        $.HN.message.alert('<spring:message code="message.yanZheng.TuiHuoSLNotDaYuDaoHSL"/>', '<spring:message code="message.HN.alert.type"/>', 'warn');
	                         return;
	                    }
		    			if ($.trim($("#retReason"+rowId).val()).length < 1){
		    			$.HN.message.alert('<spring:message code="message.yanZheng.QingTianXieTuiHuoYuanY"/>', "<spring:message code='message.HN.alert.type'/>", "warn");
		    				return;
		    			}
	                    
						if(i<3){
							approveCodes+= rowdata.approveCode+"<br/>"
							if(i==2)
							approveCodes+='...';
							
						}
						
	                    list.push({"retPlanId":rowdata.retPlanId,"returnCount":$.trim($("#returnCount"+rowdata.retPlanId).val()),"retCount":$.trim($("#retCount"+rowId).val()),"recpInfoId":rowdata.recpInfoId,"retReason":$.trim($("#retReason"+rowId).val())}); 
	                } 
					
					
					$.HN.message.confirm('确定保存以下批次号吗？<br/>'+approveCodes, '', '').on(function (e) {
                 if (e) {
		    		$.post("${ctx}/purReturnOrder/modifyReturnPlan.html", {
		    			"array" : json.jsonToString(list)
		    		}, function(result) {
		    			if (result.success) {
		    				var curpage = $("#gridlist").jqGrid('getGridParam', 'page');
		    				gridSerch();
		    				$.HN.message.alert("保存成功！", "<spring:message code="message.HN.alert.type"/>", "success");
 	    			}
		    		}, "json").error(function(err) {
		    		});
		    		}});
				}
             
    </script>
</body>
</html>